package com.union.vehicleassistant.util.update;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;

public class VersionNodeComparator implements Comparator<String> {
    private static final String ALPHA = "alpha";
    private static final String BETA = "beta";
    private static final String RC = "rc";

    @Override
    public int compare(String currentNode, String onlineNode) {
        if (TextUtils.isEmpty(currentNode) || TextUtils.isEmpty(onlineNode)) {
            return 1;
        }
        if (currentNode.equals(onlineNode)) {
            return 0;
        }
        try {
            long currentNodeValue = Long.parseLong(currentNode);
            long onlineNodeValue = Long.parseLong(onlineNode);
            if (currentNodeValue < onlineNodeValue) {
                return -1;
            } else if (currentNodeValue > onlineNodeValue) {
                return 1;
            }
        } catch (NumberFormatException e) {
            String s1 = currentNode.toLowerCase();
            String s2 = onlineNode.toLowerCase();
            List<String> currentVersions = getNumArrays(s1);
            List<String> onlineVersions = getNumArrays(s2);
            if (currentVersions.isEmpty() || onlineVersions.isEmpty()) {
                return 0;
            }
            int minLength = Math.min(currentVersions.size(), onlineVersions.size());
            for (int i = 0; i < minLength; i++) {
                String currentSecondVer = currentVersions.get(i);
                String onlineSecondVer = onlineVersions.get(i);
                int compare = compare(currentSecondVer, onlineSecondVer);
                if (0 != compare) {
                    return compare;
                }
            }
            if (s1.contains(ALPHA) && !s2.contains(ALPHA)) {
                return -1;
            } else if (!s1.contains(ALPHA) && s2.contains(ALPHA)) {
                return 1;
            } else if (s1.contains(BETA) && !s2.contains(BETA)) {
                return -1;
            } else if (!s1.contains(BETA) && s2.contains(BETA)) {
                return 1;
            } else if (s1.contains(RC) && !s2.contains(RC)) {
                return -1;
            } else if (!s1.contains(RC) && s2.contains(RC)) {
                return 1;
            }
        }
        return 0;
    }

    public static List<String> getNumArrays(String str) {
        List<String> numArrays = new ArrayList<>();
        String regEx = "[0-9]+";
        Pattern p = Pattern.compile(regEx);
        java.util.regex.Matcher m = p.matcher(str);
        while (m.find()) {
            numArrays.add(m.group());
        }
        return numArrays;
    }
}